/**
 *    Copyright 2009-2021 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.executor.statement;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;

/**
 * @author Clinton Begin
 */
public abstract class BaseStatementHandler implements StatementHandler {
  /**
   * 配置信息
   */
  protected final Configuration configuration;
  /**
   * 对象工厂，用来创建对象，
   */
  protected final ObjectFactory objectFactory;
  /**
   * 类型注册器
   */
  protected final TypeHandlerRegistry typeHandlerRegistry;
  protected final ResultSetHandler resultSetHandler;
  protected final ParameterHandler parameterHandler;
  /**
   * 执行器
   */
  protected final Executor executor;
  /**
   *  执行语句
   */
  protected final MappedStatement mappedStatement;
  /**
   * 内存分页
   */
  protected final RowBounds rowBounds;
  /**
   * 绑定sql
   */
  protected BoundSql boundSql;

  /**
   * 基本执行处理器
   * @param executor 处理器
   * @param mappedStatement 执行语句对象
   * @param parameterObject 参数信息
   * @param rowBounds 内存分页
   * @param resultHandler 结果处理器
   * @param boundSql 绑定SQL
   */
  protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    // 设置配置信息
    this.configuration = mappedStatement.getConfiguration();
    //  执行器
    this.executor = executor;
    // 执行语句
    this.mappedStatement = mappedStatement;
    // 内存分页
    this.rowBounds = rowBounds;
    // 类型注册器
    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
    // 对象工厂
    this.objectFactory = configuration.getObjectFactory();
    // 如果绑定sql为null
    if (boundSql == null) { // issue #435, get the key before calculating the statement
      // 生成key
      generateKeys(parameterObject);
      // 绑定sql
      boundSql = mappedStatement.getBoundSql(parameterObject);
    }

    this.boundSql = boundSql;
    // 参数处理器
    this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
    // 结果集合处理器
    this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
  }

  /**
   * 获取BoundSql
   * @return
   */
  @Override
  public BoundSql getBoundSql() {
    return boundSql;
  }

  /**
   * 获取参数处理器ParameterHandler
   * @return
   */
  @Override
  public ParameterHandler getParameterHandler() {
    return parameterHandler;
  }

  /**
   * 准备阶段
   * @param connection 数据库连接对象
   * @param transactionTimeout 事务超时时间
   * @return
   * @throws SQLException
   */
  @Override
  public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
    ErrorContext.instance().sql(boundSql.getSql());
    Statement statement = null;
    try {
      // 实例化
      statement = instantiateStatement(connection);
      // 设置超时时间
      setStatementTimeout(statement, transactionTimeout);
      // 设置和数据库数据交互数量
      setFetchSize(statement);
      return statement;
    } catch (SQLException e) {
      closeStatement(statement);
      throw e;
    } catch (Exception e) {
      closeStatement(statement);
      throw new ExecutorException("Error preparing statement.  Cause: " + e, e);
    }
  }

  /**
   * 实例化Statement
   * @param connection 连接对象
   * @return
   * @throws SQLException
   */
  protected abstract Statement instantiateStatement(Connection connection) throws SQLException;

  /**
   * 设置Statement超时时间
   * @param stmt Statement对象
   * @param transactionTimeout 事务超时时间
   * @throws SQLException
   */
  protected void setStatementTimeout(Statement stmt, Integer transactionTimeout) throws SQLException {
    Integer queryTimeout = null;
    if (mappedStatement.getTimeout() != null) {
      queryTimeout = mappedStatement.getTimeout();
    } else if (configuration.getDefaultStatementTimeout() != null) {
      queryTimeout = configuration.getDefaultStatementTimeout();
    }
    if (queryTimeout != null) {
      stmt.setQueryTimeout(queryTimeout);
    }
    StatementUtil.applyTransactionTimeout(stmt, queryTimeout, transactionTimeout);
  }

  /**
   * 设置FetchSize
   * @param stmt Statement对象
   * @throws SQLException
   */
  protected void setFetchSize(Statement stmt) throws SQLException {
    Integer fetchSize = mappedStatement.getFetchSize();
    if (fetchSize != null) {
      stmt.setFetchSize(fetchSize);
      return;
    }
    Integer defaultFetchSize = configuration.getDefaultFetchSize();
    if (defaultFetchSize != null) {
      stmt.setFetchSize(defaultFetchSize);
    }
  }

  /**
   * 关闭Statement
   * @param statement Statement对象
   */
  protected void closeStatement(Statement statement) {
    try {
      if (statement != null) {
        statement.close();
      }
    } catch (SQLException e) {
      //ignore
    }
  }

  /**
   * 主要是用来生成id,比如oracle进行插入的时候，如果表结构的ID是自动生成的，或者oracle一样计算出来的，
   * 那么在代码中，我们会设置userGenerator属性或者selectKey标签，这时候就需要进行计算，
   * mysql自增长不需要，但是也需要执行这一步，知识KetGenerator实现不一样罢了
   * @param parameter 参数信息,或者存放参数的对象
   */
  protected void generateKeys(Object parameter) {
    KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
    ErrorContext.instance().store();
    keyGenerator.processBefore(executor, mappedStatement, null, parameter);
    ErrorContext.instance().recall();
  }

}
